import { getStorePage, getShopSpuPage } from '../../../api/goods';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    keyword: '',
    tabIndex: 0,
    tabList: [
      {
        name: '综合',
      },
      {
        name: '店铺',
      },
    ],
    pageInfo: {
      pageNo: 1,
      pageSize: 10,
    },
    shopList: [],
    storeList: [],
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const keyword = wx.getStorageSync('searchKeyword')
    this.setData({
      keyword: keyword
    }, () => {
      wx.removeStorage({key: 'searchKeyword'})
      this.init(true)
    })    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.data.pageInfo.pageNo++;
    this.init();
  },
  keywordChange(e) {
    this.setData({
      keyword: e.detail.value,
    });
  },
  clearTap() {
    this.setData(
      {
        keyword: '',
      },
      () => {
        this.init(true);
      },
    );
  },
  searchTap(e) {
    const { fresh } = e.currentTarget.dataset;
    this.init(fresh);
  },
  changeTab(e) {
    const { index } = e.currentTarget.dataset;
    this.setData(
      {
        tabIndex: index,
      },
      () => {
        this.init(true);
      },
    );
  },
  async init(fresh = false) {
    console.log('this.data.keyword', this.data.keyword);
    if (fresh) {
      this.data.pageInfo.pageNo = 1;
    }
    const params = {
      ...this.data.pageInfo,
    };
    let data = null;
    if (this.data.tabIndex === 0) {
      params.keyword = this.data.keyword;
      data = await getShopSpuPage(params);
      data.list.map(t => {
        t.price = t.price && (t.price / 100).toFixed(2)
          return t
      })
      this.setData({
        shopList: fresh ? data.list : this.data.shopList.concat(data.list),
      });
    } else {
      params.name = this.data.keyword;
      data = await getStorePage(params);
      data.list.map(t => {
        t.products.map(u => {
          u.price = u.price ? (u.price / 100).toFixed(2) : '--'
          return u
        })      
      })
      this.setData({
        storeList: fresh ? data.list : this.data.storeList.concat(data.list),
      });
    }
  },
});
